<?php
class Controller_Admin_CPS extends Controller_Template
{
    protected $_report_types; 

    public function __construct($req, $res)
    {
        $this->template = 'smarty:channel/CPS/lists';
        $this->_report_types = array('channels', 'activities');
        parent::__construct($req, $res);
    }

    public function action_channels($attr_type = 'auto')
    {
        $this->template->set_filename($this->template_channels_name()); 

        if ($attr_type == 'auto')
            $channels = Promotion_Channel_CPS::auto_cps_game_channels();
        else
            $channels = Promotion_Channel_CPS::all_cps_game_channels();

        $this->template->set('channels', $channels);
        $this->template->set('channels_type', $attr_type);
    }

    //
    // 重置CPS渠道的游戏分成比例
    //
    // @param   int     $channel_id
    // @param   int     $ratio （比如30代表 30%)
    public function action_json_cps_game_ratio ($channel_id, $ratio)
    {
        $this->template->set_filename('smarty:util/json');
        $ratio = (int) max(0, $ratio);
        $chnid = (int) max(0, $channel_id);
        $result = NULL;

        try {
            if (empty($chnid) || empty($ratio))
                throw new Exception("invalid param");

            $ratio  = Promotion_Channel_CPS::ratio_channel($channel_id, NULL, $ratio);
            $result = array('status' => 0, 'cps_game_ratio' => $ratio);
        }
        catch (Exception $e)
        {
            $result = array('status' => 1, 'message' => 'invalid param');
        }

        $this->template->set('json', json_encode($result));
    }

    public function action_add_auto_channel ()
    {
        $post = $this->request->post();
        if (empty($post))
        {
            $this->template->set('games', Promotion_Activity_CPS::activities());
            $this->template->set_filename('smarty:channel/CPS/add'); 
        }
        else
        {
            $name = trim(Arr::get($post, 'channel_name'));
            $key1 = trim(Arr::get($post, 'union_channel_key'));
            $key2 = trim(Arr::get($post, 'yyh_channel_key'));
            $ratio= (int)(Arr::get($post, 'ratio', 0));
            $desc = trim(Arr::get($post, 'desc', ''));
            $auto = (int)(Arr::get($post, 'auto_cps_game', 0));
            $aids = Arr::get($post, 'activity_ids', array());

            $auto = $auto > 0 ? 1 : 0;
            if (! empty($key1))
                $key = 'ac.union.'.$key1;
            else
                $key = $key2;

            if (! empty($name) && ! empty($key) &&
                  ($ratio > 0 && $ratio < 100)
                )
            {
                Promotion_Channel_CPS::add_cps_game_channel($name, $key, $ratio, $desc, $auto, $aids);
            }

            $this->request->redirect('/CPS/channels');
        }
    }

    public function action_report ($type = 'channels', $day1 = NULL, $day2 = NULL)
    {
        $type = strtolower($type);
        if (! $this->valid_type($type))
            throw new HTTP_Exception_404("Not Found");

        $day1 = empty($day1) ? date("Y-m-d", time() - 86400) : date("Y-m-d", strtotime($day1));
        $day2 = empty($day2) ? $day1 : date("Y-m-d", strtotime($day2));
        $today = date("Y-m-d", time());
        $yesterday = date("Y-m-d", time() - 86400);
        $threedaysago = date("Y-m-d", time() - 86400 * 3);
        $aweekago = date("Y-m-d", time() - 86400 * 7);
        $amonthago = date("Y-m-d", time() - 86400 * 30);

        $this->template->set_filename($this->template_report_name());
        $result = $this->get_report($type, $day1, $day2);
        $this->template->set('param', array($type,$day1,$day2));
        $this->template->set('report_sub_type', $this->report_type($type));
        $this->template->set('report_items', $result);
        $this->template->set('report_summary', $this->report_summary($result));
        $this->template->set('report_days', $this->build_days($day1, $day2));
        $day_array = array(
        		'start_day' => str_replace('-','/',$day1),
        		'end_day' => str_replace('-','/',$day2),
        		'today' => $today,
        		'yesterday' => $yesterday,
        		'threedaysago' => $threedaysago,
        		'aweekago' => $aweekago,
        		'amonthago' => $amonthago,
        		);
        $this->template->set('day', $day_array);
    }
    
    public function action_has_channel()
    {
    	$post = $this->request->query();
    	$channel = Arr::get($post,'channel');
    	$rs = Promotion_Channel::has_channel($channel);
    	print_r (json_encode($rs));
    	exit;
    }

    public function action_pkgtool ($action = NULL, $param = NULL)
    {
        if (empty($action))
        {
            $pkgs = Promotion_Pkgtool_CPS::currents();
            $this->template->set_filename('smarty:channel/CPS/tools/packages');
            $this->template->set('packages', $pkgs);
        }
        else if ($action == 'sync')
        {
            Promotion_PkgTool_CPS::sync();
            $this->request->redirect('/CPS/pkgtool');
        }
        else if ($action == 'rebuild')
        {
            $pname = trim($param);
            if (! empty($pname))
                Promotion_PkgTool_CPS::rebuild_package($pname);
            $this->request->redirect('/CPS/pkgtool');
        }
        else if ($action == 'rebuild_all')
        {
            Promotion_PkgTool_CPS::rebuild_all_packages();
            $this->request->redirect('/CPS/pkgtool');
        }
    }

 

    private function build_days ($start, $stop)
    {
        $show = '';
        if ($start == $stop)
            $show = $start;
        else
        {
            $d1 = date("m-d", strtotime($start));
            $d2 = date("m-d", strtotime($stop));

            $show = "$d1 ... $d2";
        }

        return array(
            'show' => $show,
            'start' => $start,
            'stop'  => $stop,
        );
    }


    private function report_type ($type)
    {
        return in_array($type, $this->_report_types) ? $type : 'detail';
    }

    protected function report_summary (& $items)
    {
        $sum = array();
        foreach ($items as & $item)
        {
            if (! isset($item['money']))
                continue;

            foreach ($item['money'] as $k => $v)
            {
                if (! isset($sum[$k]))
                    $sum[$k] = 0;

                $sum[$k] += $v;
            }

            if (isset($item['downs']))
                $sum['downs'] += $item['downs'];
        }

        return $sum;
    }

    protected function get_report ($type, $day1, $day2)
    {
        return Promotion_Effect_CPS::factory($type)->report($day1, $day2);
    }

    protected function template_report_name ()
    {
        if (site::type() == 'merchant')
            return 'smarty:effect/CPS/merchant/report';
        else
            return 'smarty:effect/CPS/report';
    }

    protected function template_channels_name ()
    {
        return 'smarty:channel/CPS/lists';
    }


    protected function valid_type ($type)
    {
        if (! in_array($type, $this->_report_types) && ! Promotion_Channel::has_channel($type))
            return FALSE;
        else
            return TRUE;
    }
}
